#!/usr/bin / env node

/*
 * @Autor: mofish
 * @Date: 2022-08-25 10:25:02
 * @LastEditors: mofish
 * @LastEditTime: 2022-08-25 14:05:17
 * @Description: 初始化脚手架
 */
const path = require("path");
const fs = require("fs");
const { promisify } = require("util");
const ora = require("ora");
const chalk = require("chalk");
const inquirer = require("inquirer");
const {
  continueToInstall,
  installTool,
  projectInfo,
} = require("./utils/inquirerPrompt");
const download = require("./utils/downloadGitRepo");
const install = require("./utils/install");

const exist = promisify(fs.stat);

const init = async function (projectName) {
  const projectExist = await exist(projectName).catch((err) => {
    // 处理除文件已存在之外的其他错误
    if (err.code !== "ENOENT") {
      console.log(chalk.redBright.bold(err));
    }
  });
  // 文件已存在
  if (projectExist) {
    console.log(chalk.redBright.bold("The file has exited！"));
    return;
  }
  const { description, author } = await inquirer.prompt(projectInfo);
  const loading = ora("downloading template...");
  loading.start();
  loading.color = "yellow";
  /* 下载模板 */
  download(projectName).then(
    async () => {
      loading.succeed();
      const fileName = `${projectName}/package.json`;
      if (await exist(fileName)) {
        /* 根据输入信息，改变package.json */
        const data = fs.readFileSync(fileName).toString();
        let json = JSON.parse(data);
        json.name = projectName;
        json.author = author;
        json.description = description;
        fs.writeFileSync(fileName, JSON.stringify(json, null, "\t"), "utf-8");
        console.log(chalk.green("Project initialization finished!"));
        console.log();

        const { next } = await inquirer.prompt(continueToInstall);
        if (next) {
          const { tool } = await inquirer.prompt(installTool);
          console.log(chalk.yellowBright("start install dependencies..."));
          /* 安装项目依赖 */
          await install({
            cwd: path.join(process.cwd(), projectName),
            command: tool,
          }).then(
            () => {
              console.log();
              console.log("We suggest that you begin by typing:");
              console.log();
              console.log(chalk.cyan("  cd"), projectName);
              console.log(`  ${chalk.cyan(`${tool} start`)}`);
            },
            () => {
              console.log(chalk.redBright.bold("install fail!"));
            }
          );
        }
      }
    },
    () => {
      loading.fail();
    }
  );
};

module.exports = init;
